/* 利用条件变量实现的倒计时门闩类 CountDownLatch的主要作用是确保Thread类中，
执行thread_create()函数，回调函数func真的启动了以后外层的start()函数才返回*/
#pragma once
#include "Condition.h"
#include "MutexLock.h"
#include "NonCopyable.h"

class CountDownLatch : noncopyable {
 public:
  explicit CountDownLatch(int count)
      : mutex_(), condition_(mutex_), count_(count) {}
  /*此处有先后顺序，mutex_要先于condition_构造，并作为后者的构造参数*/
  void wait() {
    MutexLockGuard lock(mutex_);
    while (count_ > 0) condition_.wait();
  }
  void countDown() {
    MutexLockGuard lock(mutex_);
    --count_;
    if (count_ == 0) condition_.notifyAll();
  }

 private:
  mutable MutexLock mutex_;
  // mutable关键字表示变量mutex_在const函数中也可以被修改
  Condition condition_;
  int count_;
};